<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  users
 */

class m_users_actions_block_ChangePasswordAction extends  m_backoffice_extends_Action
{
	public function execute()
	{
		$superUser = $this->getDocumentProvider()->loadDocuments("modules_users/user")->retrieveFirstDocument();
		$user = $this->getRequestDocument();
		$currentUser = $this->getUser();
		$errors = array();
		$values = $this->getFormValues("formPassword");
        $key = m_backoffice_services_BackOfficeService::getKey();

		if($user && $values["submit"] == "generate")
		{
			$newPassword = f_utils_String::generateString();
            $message = "Le mot de passe pour l'utilisateur ".$user->getLogin()." a été réinitialisé<br />";
			$message .= "Voici votre nouveau mot de passe : $newPassword";
			
			$mail = f_mail_MailService::getInstance();
			$mail->setSenderName("Admin")

				 ->setSender($superUser->getEmail())
				 ->setSubject("Changement de mot de passe")
				 ->setReceiverName($user->getFirstname() . " " . $user->getLastname())
				 ->setReceiver($user->getEmail())
				 ->setSubject("Votre nouveau mot de passe")
				 ->setHtmlAndTextBody($message)
				 ->send();
			
			if($mail)
			{
				$user->setPassword(md5($newPassword.$key))->save();
				$errors["status"] = "success";
				$errors['info'] = 'Le mot de passe a été changé.';
			}
			else
			{
				$errors['info'] = "Erreur lors de l'envoie du mail.";
			}
		}
		elseif($user && $values["submit"] == "change")
		{
			$password = $values["password"];
			$password2 = $values["password2"];
			$oldPassword = $values["oldPassword"].$key;
			$boolPass = $user->getPassword() == md5($oldPassword) ? true : false;
			
			if(empty($oldPassword) || empty($password) || empty($password2))
			{
				$errors["info"] = "Tous les champs doivent être saisis";
			}
			elseif(!$boolPass)
			{
				$errors["info"] = "L'ancien mot de passe est incorrect";
			}
			elseif($password !== $password2)
			{
				$errors["info"] = "Les champs doivent être identiques";
			}
			
			if(empty($errors))
			{
				$user->setPassword(md5($password.$key))->save();
				$errors["status"] = "success";
				$errors["info"] = 'Le mot de passe a été changé.';
			}
		}

        //Template choice
		if($currentUser->getUniqueId() == $user->getUniqueId())
		{
			$template = "ChangePassword";
		}
		else
		{
			$template = "GeneratePassword";
			$disableDeletion = false;
			$errors[] = "Le mot de passe sera envoyé à l'adresse de messagerie de l'utilisateur.";
		}

		$this->addToModel("template", $template);
		$this->addToModel("errors", $errors);
		$this->addToModel("user", $user);
		$this->addToModel("href", $this->getRequestParameter("href"));

		$this->setView('success');
	}	
	
	public function validate()
	{
        $user =  $this->getRequestDocument();
        return ($this->getUserContext()->hasRight(array("backoffice_accessBo","users_ChangePassword")) || $this->getUser()->getUniqueId() === $user->getUniqueId());
	}
}